package controllers.games;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JButton;

import models.games.ConfrontoRapido;
import views.games.ConfrontoRapidoView;
import core.GameLauncher;
import core.GameLauncher.State;

public class ConfrontoRapidoController implements KeyListener, ActionListener {

	private ConfrontoRapido model;
	private ConfrontoRapidoView view;
	private boolean started = false;
	private GameLauncher gameLauncher;

	public ConfrontoRapidoController(ConfrontoRapido model,
			ConfrontoRapidoView view, GameLauncher gameLauncher) {
		this.model = model;
		this.gameLauncher = gameLauncher;
		this.view = view;
		view.addKeyListenerToGame(this);
		view.addActionListenerToGame(this);
	}

	@Override
	public void keyPressed(KeyEvent e) {
		boolean answer = false;
		if (view.isAnimating())
			return;
		if (started && (e.getKeyCode() == KeyEvent.VK_LEFT)) {// NO
			answer = model.elaborateAnswer(false);
			view.setScore(model.getScore());
			view.setOther("x" + model.getScoreMultiplier());
			view.updateInternalPanel(model.getCurrentImage());
		}
		if (started && (e.getKeyCode() == KeyEvent.VK_RIGHT)) {// SI
			answer = model.elaborateAnswer(true);
			view.setScore(model.getScore());
			view.setOther("x" + model.getScoreMultiplier());
			view.updateInternalPanel(model.getCurrentImage());
		}
		if (answer) {
			gameLauncher.correctAnswer();
		}
		if (!started && e.getKeyCode() == KeyEvent.VK_ENTER) {
			view.startTimer();
			view.updateInternalPanel(model.getCurrentImage());
			model.firstRound();
			view.activateButtons();
			started = true;
		}
	}

	@Override
	public void keyReleased(KeyEvent e) {
	}

	@Override
	public void keyTyped(KeyEvent e) {
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (view.isAnimating())
			return;
		JButton input = (JButton) e.getSource();
		String inputText = input.getText();
		if (started && inputText.equalsIgnoreCase("NO")) {
			model.elaborateAnswer(false);
		}
		if (started && inputText.equalsIgnoreCase("SI")) {
			model.elaborateAnswer(true);
		}
		if (started) {
			view.setScore(model.getScore());
			view.setOther("x" + model.getScoreMultiplier());
			view.updateInternalPanel(model.getCurrentImage());
		}
		if (inputText.equals("Ricomincia")) {
			ConfrontoRapido newModel = new ConfrontoRapido(
					model.getCurrentUser());
			ConfrontoRapidoView newView = new ConfrontoRapidoView();
			ConfrontoRapidoController newController = new ConfrontoRapidoController(
					newModel, newView, gameLauncher);
			gameLauncher.setGame(newModel, newView, newController);
			gameLauncher.startTransition(State.GAME);
			model.addGameToDatabase();
			System.out.println("Ricomincia");
		}

		if (inputText.equals("Menu Giochi")) {
			gameLauncher.startTransition(State.GAME_MENU);
			model.addGameToDatabase();
			System.out.println("Menu Giochi");
		}

	}
}